package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: atguigu
 * @create: 2023-12-02 09:21
 */
@Slf4j
@Component("1003")
public class VIPStrategy  implements PaidRecordStrategy {

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    /**
     * 处理购买类型是VIP
     * @param userPaidRecordVo
     */
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("[用户服务]处理购买类型是VIP");
        //3.处理会员购买记录
        //3.1 新增VIP会员购买记录
        //3.1.0 获取会员套餐信息
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
        //3.1.1 获取当前用户信息 得到当前用户VIP状态及VIP过期时间
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        //3.1.2 动态获取会员生效时间及过期时间
        Date now = new Date();
        Date expireDate = new Date();
        //3.1.3 构建用户购买VIP记录对象
        UserVipService userVipService = new UserVipService();
        if(userInfo.getIsVip().intValue()==1 && userInfo.getVipExpireTime().after(now)){
            //用户身份已是VIP会员
            expireDate = DateUtil.offsetMonth(userInfo.getVipExpireTime(), vipServiceConfig.getServiceMonth());
            //本次购买VIP会员生效时间：是原来会员过期时间
            userVipService.setStartTime(userInfo.getVipExpireTime());
            //本次购买VIP会员过期时间：原来会员过期时间+购买VIP套餐月数
            userVipService.setExpireTime(expireDate);
        }else{
            //普通用户
            //本次购买VIP会员生效时间:当前时间
            userVipService.setStartTime(now);
            //本次购买VIP会员过期时间:当前时间+购买VIP套餐月数
            userVipService.setExpireTime(DateUtil.offsetMonth(now, vipServiceConfig.getServiceMonth()));
        }
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userPaidRecordVo.getUserId());
        //3.3.4 保存会员购买记录
        userVipServiceMapper.insert(userVipService);

        //3.2 更新用户VIP标识及会员过期时间
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        userInfoMapper.updateById(userInfo);
    }
}
